// 全局vuex
import http from '@/http';

const app = {
  state: {
    hasLogin: false, // 用户是否已经登录
    token: '', // 登录凭证
    // 用户信息
    userInfo: {},
    // 用户会员、书单、书币信息
    baseInfo: {
      amount: 0,
      books: 0,
      member: {}
    },
    redirect: {
      type: 'switchTab',
      url: encodeURIComponent('/pages/index/index')
    },
    settings: {}, // 应用设置
    hasUpdate: false // 是否有新版本可以更新
  },
  mutations: {
    // 登入
    login(state, payload) {
      state.hasLogin = true;
      state.token = payload.token;
      // TODO 写入
      state.userInfo = payload.userInfo;
      // 缓存用户登陆状态
      if (payload.cache) {
        uni.setStorageSync('expiredTime', Date.now() + 24 * 60 * 60 * 1000);
        uni.setStorageSync('token', payload.token);
        uni.setStorageSync('userInfo', payload.userInfo);
      }
    },

    // 登出
    logout(state) {
      state.hasLogin = false;
      state.token = '';
      state.userInfo = {};
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
    },

    // 更新登录redirect url
    updateRedirectUrl(state, payload) {
      state.redirect.type = payload.type || 'switchTab';
      state.redirect.url = payload.url || encodeURIComponent('/pages/index/index');
    },

    // 更新用户信息
    updateUserInfo(state, payload) {
      const newData = { ...state.userInfo, ...payload };
      state.userInfo = newData;
      uni.setStorageSync('userInfo', newData);
    },

    // 更新基础用户信息
    updateBaseInfo(state, payload) {
      state.baseInfo = { ...state.baseInfo, ...payload };
    },

    // 更新设置
    updateSettings(state, payload) {
      state.settings = { ...state.settings, ...payload };
    },

    setHasUpdate(state, hasUpdate) {
      state.hasUpdate = !!hasUpdate;
    }
  },
  actions: {
    getAppSettings({ commit }) {
      const errorHandler = function () {
        uni.showModal({
          title: '获取应用设置失败',
          content: '这些配置可能影响页面功能使用，请尝试退出微信重新进入小程序',
          showCancel: false
        });
      };
      http({
        method: 'GET',
        url: '/api/front/settings',
        needAuth: false,
        skipToast: true
      })
        .then(res => {
          if (res.ok) {
            commit('updateSettings', res.data);
          } else {
            errorHandler();
          }
        })
        .catch(err => {
          errorHandler();
        });
    }
  }
};

export default app;
